﻿//生成[Material]Service代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FineAdmin.IService;
using FineAdmin.Model;
using FineAdmin.IRepository;
using FineAdmin.Common;
using Top.Api;
using Top.Api.Request;
using HuiJI.Tools.TBK;
using FastJSON;
using Top.Api.Response;
using System.Data.Objects;

namespace FineAdmin.Service
{
    public class MaterialService : BaseService<MaterialModel>, IMaterialService
    {
        public IOpRecordService OpRecordService { get; set; }
        public IMaterialRepository MaterialRepository { get; set; }
        public IMaterialGoodsRepository MaterialGoodsRepository { get; set; }
        public IAdZoneRepository AdZoneRepository { get; set; }
        public ISystemParameterRepository SystemParameterRepository { get; set; }
        public IEnumerable<MaterialModel> GetMaterialList()
        {
            return MaterialRepository.GetMaterialList();
        }


        public dynamic GetListByFilter(MaterialModel filter, PageInfo pageInfo)
        {
            string _where = " where 1=1";
            return GetListByFilter(filter, pageInfo, _where);
        }

        public int RefreshData(int id = -1, bool OnlyAuto = false, bool Unify = false)
        {

            int ret = 0;
            if (id != -1)
            {
                ret = UpdateMaterialGoodsByMaterialId(id);
            }
            else
            {
                //获取所有的精选物料ID
                var materialList = MaterialRepository.GetAll();
                if (OnlyAuto)
                {
                    //筛选 启用了自动更新
                    materialList = materialList.Where(m => m.IsEnable == true && m.IsEnableAutoUpdate == true).ToList();
                    //筛选出超时需要更新的 
                    //materialList = materialList.Where(m => m.LastUpdate == null || (EntityFunctions.DiffMinutes(m.LastUpdate, DateTime.Now) > m.UpdateInterval)).ToList();
                    if (!Unify)
                    {
                        materialList = materialList.Where(m => m.LastUpdate == null || ((DateTime.Now - m.LastUpdate.Value).TotalMinutes > m.UpdateInterval)).ToList();
                    }

                }
                else
                {
                    materialList = materialList.Where(m => m.IsEnable == true).ToList();
                }

                foreach (var item in materialList)
                {
                    ret += UpdateMaterialGoodsByMaterialId(item.Id);
                }

            }
            return ret;
        }


        private int UpdateMaterialGoodsByMaterialId(int id)
        {
            //RedisHelper rhelper = new RedisHelper(1);
            int ret = 0;
            if (id != -1)
            {
                //指定更新
                //更新部分
                var MaterialData = MaterialRepository.GetById(id);

                MaterialData.LastUpdate = DateTime.Now;

                MaterialRepository.UpdateById(MaterialData);//更新上次更新时间

                string Api_Url = SystemParameterRepository.GetByCode("TBK_API").SPValue;
                var adzList = AdZoneRepository.GetAdZoneList();
                var adzDefault = adzList.FirstOrDefault(m => m.IsDefault == true && m.Type == 1);
                TBKTools tbk_tools = new TBKTools(Api_Url);
                DateTime now = DateTime.Now;

                int PageSize = 100;//页大小
                int PageNo = 1;//页码
                //int RequestsCount = 0;// 请求次数

                //是否设定了商品总数
                if (MaterialData.Quantity != null && MaterialData.Quantity.Value != 0)
                {


                    if (MaterialData.Quantity < 100)
                    {
                        //限制数量小于100 则 只请求一次
                        PageSize = MaterialData.Quantity.Value;
                        PageNo = 1;
                    }
                    else
                    {
                        PageNo = (int)Math.Ceiling((double)MaterialData.Quantity.Value / 100);
                    }
                }

                //是否设定了获取商品总数 优先级高
                if (MaterialData.LimitQuantity != null && MaterialData.LimitQuantity.Value != 0)
                {
                    if (MaterialData.LimitQuantity < 100)
                    {
                        //限制数量小于100 则 只请求一次
                        PageSize = MaterialData.LimitQuantity.Value;
                        PageNo = 1;
                    }
                    else
                    {
                        PageNo = (int)Math.Ceiling((double)MaterialData.LimitQuantity.Value / 100);
                    }

                }



                //List<TbkDgOptimusMaterialResponse> TbkDgOpMa = new List<TbkDgOptimusMaterialResponse>();
                for (int i = 0; i < PageNo; i++)
                {
                    var rsp = tbk_tools.Material(adzDefault.TBK_AppKey, adzDefault.TBK_AppSecret, (long)adzDefault.TBK_AdzoneId, (long)MaterialData.MaterialId, PageSize, i + 1, null);

                    OpRecordService.AddOpRecord("物料精选", "淘宝客API", 1);

                    foreach (var item in rsp.ResultList)
                    {
                        if (MaterialData.LimitQuantity != null && MaterialData.LimitQuantity.Value != 0 && MaterialData.LimitQuantity.Value <= ret)
                        {
                            //终止循环
                            break;
                        }



                        bool isExist = HuiJIRedisService.MaterialGoodsExists(MaterialData.Id.ToString(), item.ItemId.ToString());//rhelper.KeyExists("item:" + "M" + MaterialData.Id + ":ItemID" + item.ItemId);

                        if (!isExist)
                        {

                            var mgood = new MaterialGoodsModel()
                            {
                                CategoryId = (int)item.CategoryId,
                                CategoryName = item.CategoryName,
                                ClickUrl = item.ClickUrl,
                                CommissionRate = item.CommissionRate,
                                CouponAmount = (int)item.CouponAmount,
                                CouponInfo = item.CouponInfo,
                                CouponRemainCount = (int)item.CouponRemainCount,
                                CouponShareUrl = item.CouponShareUrl,
                                CouponStartFee = item.CouponStartFee,

                                CouponTotalCount = (int)item.CouponTotalCount,
                                CreateTime = DateTime.Now,
                                CreateUserId = 1,
                                FavoritesInfo = JSON.ToJSON(item.FavoritesInfo),
                                ItemDescription = item.ItemDescription,
                                ItemId = item.ItemId.ToString(),
                                LevelOneCategoryId = (int)item.LevelOneCategoryId,
                                LevelOneCategoryName = item.LevelOneCategoryName,
                                Material_id = MaterialData.MaterialId,
                                Mid = MaterialData.Id,
                                Nick = item.Nick,
                                PictUrl = item.PictUrl,
                                ReservePrice = item.ReservePrice,
                                SalePrice = item.SalePrice,
                                SellerId = item.SellerId.ToString(),
                                ShopTitle = item.ShopTitle,
                                ShortTitle = item.ShortTitle,
                                SmallImages = JSON.ToJSON(item.SmallImages),
                                Title = item.Title,
                                TmallPlayActivityEndTime = item.TmallPlayActivityEndTime,
                                TmallPlayActivityStartTime = item.TmallPlayActivityStartTime,
                                UpdateTime = DateTime.Now,
                                UpdateUserId = 1,
                                UserType = (int)item.UserType,
                                Volume = (int)item.Volume,
                                WhiteImage = item.WhiteImage,
                                WordList = JSON.ToJSON(item.WordList),
                                ZkFinalPrice = decimal.Parse(item.ZkFinalPrice),
                                CouponAfterPrice = decimal.Parse(item.ZkFinalPrice) - (decimal)item.CouponAmount,

                                CouponStartTime = GetTime(item.CouponStartTime),
                                CouponEndTime = GetTime(item.CouponEndTime)

                            };
                            var columnId = MaterialGoodsRepository.Insert(mgood);

                            mgood.Id = columnId;

                            //rhelper.StringSet("item:" + "M" + MaterialData.Id + ":ItemID" + item.ItemId, JSON.ToJSON(mgood));
                            HuiJIRedisService.MaterialGoodsSet(mgood);
                        }
                        else
                        {
                            var sameItemIdList = MaterialGoodsRepository.GetMaterialGoodsByItemID(item.ItemId.ToString()).ToList();

                            sameItemIdList = sameItemIdList.Where(m => m.Mid == MaterialData.Id).ToList();

                            foreach (var sameitem in sameItemIdList)
                            {
                                var index = sameItemIdList.IndexOf(sameitem);
                                if (index == 0)
                                {
                                    //更新
                                    sameitem.Volume = (int)item.Volume;
                                    sameitem.UpdateTime = DateTime.Now;
                                    sameitem.ZkFinalPrice = decimal.Parse(item.ZkFinalPrice);
                                    sameitem.ClickUrl = item.ClickUrl;
                                    sameitem.CouponRemainCount = (int)item.CouponRemainCount;
                                    MaterialGoodsRepository.UpdateById(sameitem);

                                    //rhelper.StringSet("item:" + "M" + sameitem.Mid + ":ItemID" + sameitem.ItemId, JSON.ToJSON(sameitem));
                                    HuiJIRedisService.MaterialGoodsSet(sameitem);
                                }
                                else
                                {
                                    //删除
                                    MaterialGoodsRepository.DeleteById(sameitem.Id);
                                }
                            }
                        }

                        ret += 1;
                    }
                }
            }
            return ret;
        }


        private static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }
    }

}